<template>
  <div>
    <!-- 用户列表区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 搜索区域 -->
      <el-row>
        <el-col :span="10">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="userList.query"
            clearable
            @clear="search()"
          >
            <el-button slot="append" icon="el-icon-search" @click="search()"></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="addUserDialog">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 列表区域 -->
      <el-table :data="users" style="width: 100%" border stripe>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <!-- 姓名 -->
        <el-table-column prop="username" label="姓名"></el-table-column>
        <!-- 邮箱 -->
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <!-- 电话 -->
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <!-- 状态 -->
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editDialogForm(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleUser(scope.row.id)"
            ></el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showSetRoleDialog(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="userList.pagenum"
        :page-sizes="[1, 5, 10, 20]"
        :page-size="userList.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="50%">
      <div class="setleft">
        <span>
          <p>
            <strong>用户名称：</strong>
            &nbsp;{{roleInfo.username}}
          </p>
          <p>
            <strong>当前角色：</strong>
            &nbsp;{{roleInfo.role_name}}
          </p>
          <el-select v-model="selectedRoleId" placeholder="请选择角色">
            <el-option
              :label="item.roleName"
              :value="item.id"
              v-for="item in allRoleInfo"
              :key="item.id"
            ></el-option>
          </el-select>
        </span>
      </div>
      <span slot="footer" class="dialog-footer">
        <!-- 按钮区域 -->
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="resetRole()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户信息对话框 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%">
      <el-form ref="editFormRef" :model="editForm" label-width="80px" :rules="editFormRules">
        <el-form-item label="名称">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="resetEditFrom()">取 消</el-button>
        <el-button type="primary" @click="editUser()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加用户信息Dialog对话框 -->

    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close="addDialogClose()">
      <span>
        <el-form ref="addFormRef" :model="addForm" label-width="80px" :rules="addRules">
          <el-form-item label="名称" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <!-- prop必须加在el-form-item上-->
          <el-form-item label="密码" prop="password">
            <!-- 可以给input表单添加 type="password"-->
            <el-input v-model="addForm.password" type="password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      userList: {
        query: "",
        pagenum: 1,
        pagesize: 5,
      },
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      addRules: {
        username: [
          { required: true, message: "请输入名称", trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "长度在 3 到 15 个字符",
            trigger: "blur",
          },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
        mobile: [
          { required: true, message: "请输入电话号码", trigger: "blur" },
        ],
      },
      setRoleDialogVisible: false,
      pagenum: 0,
      total: 0,
      users: [],
      dialogVisible: false,
      editDialogVisible: false,
      editForm: {},
      roleInfo: {},
      allRoleInfo: [],
      selectedRoleId: "",
      editFormRules: {
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    // 更新用户角色
    async resetRole() {
      // 发起网络请求分配用户角色
      const { data: res } = await this.$http.put(
        `users/${this.roleInfo.id}/role`,
        {
          rid: this.selectedRoleId,
        }
      );
      if (res.meta.status !== 200) {
        this.setRoleDialogVisible = false;
        return this.$message.error(res.meta.msg);
      }
      console.log(res.data);
      this.$message.success(res.meta.msg);
      // 清空当前角色信息
      this.roleInfo = "";
      this.setRoleDialogVisible = false;
      this.getUserList();
    },
    // 显示分配角色的对话框
    async showSetRoleDialog(role) {
      this.setRoleDialogVisible = true;

      this.roleInfo = role;
      //请求全部角色列表
      const { data: res } = await this.$http.get("roles");
      this.allRoleInfo = res.data;
    },
    async getUserList() {
      const { data: res } = await this.$http.get("/users", {
        params: this.userList,
      });

      if (res.meta.status !== 200) {
        this.$message.error("获取用户管理列表失败!");
      }
      this.pagenum = res.data.pagenum;
      this.total = res.data.total;
      this.users = res.data.users;
    },
    // 显示编辑用户信息的表单
    async editDialogForm(id) {
      console.log(id);
      this.editDialogVisible = true;
      // 通过id获取用户完整信息
      const { data: res } = await this.$http.get("users/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("获取用户信息失败!");
      }
      this.editForm = res.data;
      console.log(res);
    },

    handleSizeChange(val) {
      console.log(val);
      this.userList.pagesize = val;
      this.getUserList();
    },
    handleCurrentChange(val) {
      console.log(val);
      this.userList.pagenum = val;
      this.getUserList();
    },
    // 重置修改用户信息的表单
    resetEditFrom() {
      this.$refs.editFormRef.resetFields();
    },
    // 删除用户信息
    async deleUser(id) {
      // 根据id发起网络请求 删除用户信息
      const { data: res } = await this.$http.delete("users/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      this.$message.success("删除成功！");
      this.getUserList();
    },

    // 修改用户信息
    editUser() {
      // 预校验
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        // 发起网络数据请求

        const { data: res } = await this.$http.put(
          "users/" + this.editForm.id,
          {
            id: this.editForm.id,
            email: this.editForm.email,
            mobile: this.editForm.mobile,
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("修改用户信息失败！");
        }
        this.editDialogVisible = false;
        this.getUserList();
        this.$message.success("修改用户信息成功！");
      });
    },
    // dialog的close事件回调函数
    addDialogClose() {
      this.$refs.addFormRef.resetFields();
    },
    // 添加用户
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        //发起网络数据请求
        const { data: res } = await this.$http.post("users", this.addForm);
        if (res.meta.status !== 201) {
          this.$message.error("添加用户失败!");
        }
        this.dialogVisible = false;
        this.getUserList();
      });
    },
    async userStateChange(userInfo) {
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      );
      console.log(res);
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state;
        this.$message.error("修改用户状态失败!");
      }

      this.$message.success("修改用户状态成功!");
    },

    search() {
      console.log("here");
      this.getUserList();
    },
    addUserDialog() {
      this.dialogVisible = true;
    },
  },
};
</script>

<style lang="less" scoped>
.el-breadcrumb {
  margin-bottom: 7px;
}
.el-card {
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15) !important;
}
.el-table {
  margin-top: 10px;
}
.setleft {
  text-align: left;
  font-size: 16px;
}
</style>